$(function() {
  class ShopCart {
    constructor() {
      this.init();
    }
    init() {
      //获取cookie中的当前用户id
      this.id = cookie('id') ? cookie('id') : null;
      this.token = cookie('token') ? cookie('token') : null;
      this.ifLogin();
      this.renderShopCart();
      this.initDom();
      this.showCartTotalCount();
      this.getSubtotal();
      this.getTotalPrice();
      // 改写成事件委托; 
      this.bindEvent();
    }
    initDom() {
      //获取购物车全部商品
      this.cartTotalCount = $('#my-content-wrapper .title .total_goods');
      //获取所有全选按钮
      this.selectAll = $('.choose_all input');
      //获取所有单选按钮
      this.chooseOne = $('.cart-item .check_box input');
      //获取计数器
      this.counter = $('.cart-item .goods_counter');
      //获取删除按钮
      this.deletes = $('.cart-item .delete');
      //删除选中商品的按钮
      this.deleteSelect = $('#my-content-wrapper .cart_foot .delete_checked');
      //清空购物车按钮
      this.clearCart = $('#my-content-wrapper .cart_foot .clear_cart');
      //已选中商品数
      this.alreadySelect = $('#my-content-wrapper .cart_foot .tip .choose_count');
      //总计容器
      this.totalPrice = $('#my-content-wrapper .cart_foot .total_price span');
    }
    bindEvent() {
      let _this = this;
      //全选按钮事件
      this.selectAll.on('click', function() {
        //让所有全选按钮同步
        _this.selectAll.each((i, item) => {
          item.checked = $(this).prop('checked');
        });
        //让所有单选按钮同步
        _this.chooseOne.each((i, item) => {
          item.checked = $(this).prop('checked');
        });
        _this.getGoodsSelect();
        _this.getTotalPrice();
      });
      //单选按钮事件
      this.chooseOne.on('click', function() {
        //让所有全选按钮选中
        _this.selectAll.each((i, item) => {
          item.checked = true;
        });
        //遍历单选按钮有一个没选中，则全选不选中
        _this.chooseOne.each((i, item) => {
          if(!item.checked) {
            _this.selectAll.each((i, item) => {
              item.checked = false;
            });
            return;
          }
        });
        _this.getGoodsSelect();
        _this.getTotalPrice();
      });
      //计数器事件
      //减量
      this.counter.on('click', '.dec', function() {
        let value = $(this).siblings('.count').children('input').val();
        if(value <= 1) {
          return;
        }
        value--;
        $(this).siblings('.count').children('input').val(value);
        //计算小计
        _this.getSubtotal();
        //计算总价
        _this.getTotalPrice();
        //更新本地存储购物车商数目
        _this.putCartOptions($(this).parents('.cart-item'));
      });
      //增量
      this.counter.on('click', '.inc', function() {
        let value = parseInt($(this).siblings('.count').children('input').val());
        let max = parseInt($(this).parent().siblings('.goods_category').find('.store-count').text().trim());
        if(value >= max) {
          $(this).siblings('.count').children('input').val(max);
          return;
        }
        value++;
        $(this).siblings('.count').children('input').val(value);
        //计算小计
        _this.getSubtotal();
        _this.getTotalPrice();
        //更新本地存储购物车商数目
        _this.putCartOptions($(this).parents('.cart-item'));
      });
      //计数输入框事件
      this.counter.on('change', '.count input', function() {
        let value = $(this).val();
        let max = parseInt($(this).parents('.goods_counter').siblings('.goods_category').find('.store-count').text().trim());
        if(value < 1) {
          $(this).val(1);
        }
        if(value > max) {
          $(this).val(max);
        }
        //计算小计
        _this.getSubtotal();
        _this.getTotalPrice();
        //更新本地存储购物车商数目
        _this.putCartOptions($(this).parents('.cart-item'));
      });
      //删除按钮
      this.deletes.on('click', function() {
        $(this).parents('.cart-item').remove();
        _this.showCartTotalCount();
        _this.getGoodsSelect();
        _this.getTotalPrice();
        _this.deleteLocalOne($(this).parents('.cart-item').attr('data-goodsid'), _this.transformParams($(this).parents('.cart-item')));
      });
      //删除部分按钮
      this.deleteSelect.on('click', function() {
        _this.deleteSelectHandle();
        _this.showCartTotalCount();
        _this.getGoodsSelect();
        _this.getTotalPrice();
      });
      //清空购物车
      this.clearCart.on('click', function() {
        $('#my-content-wrapper .cart_body').empty();
        _this.showCartTotalCount();
        _this.getGoodsSelect();
        _this.getTotalPrice();
        _this.clearlocal();
      });
    }
    //显示购物车商品总数
    showCartTotalCount() {
      this.cartTotalCount.text($('.cart-item').length);
    }
    //获取选中的商品数
    getGoodsSelect() {
      let count = 0;
      $('.cart-item').each((i, item) => {
        if($(item).find('.check_box input').prop('checked')) {
          count++;
        }
      });
      this.alreadySelect.text(count);
    }
    //删除选中商品
    deleteSelectHandle() {
      let idarr = [];
      $('.cart-item').each((i, item) => {
        if($(item).find('.check_box input').prop('checked')) {
          idarr.push({
            goodsId: $(item).attr('data-goodsid'),
            params: this.transformParams($(item))
          });
          $(item).remove();
        }
      });
      this.deletelocalSelect(idarr);
    }
    //计算总计
    getTotalPrice() {
      let total = 0;
      $('.cart-item').each((i, item) => {
        if($(item).find('.check_box input').prop('checked')) {
          total += parseFloat($(item).find('.subtotal').text().trim().slice(1));
        }
      });
      this.totalPrice.text('￥' + total.toFixed(2));
    }
    //渲染购物车
    renderShopCart() {
      let cartParams = JSON.parse(localStorage.getItem(this.id));
      if(cartParams && cartParams.length > 0) {
        $('#my-content-wrapper .cart_body').html(cartParams.map(item => {
          let parastr = '';
          for(let attr in item.params) {
            parastr += `
              <li class='fl'>
                <span class='params-key'>${attr}</span>:
                <span class='params-value'>${item.params[attr]}</span>
              </li>
            `; 
          }
          return `
          <div class="cart-item" data-goodsid="${item.goodsid}">
            <div class="check_box fl">
              <input type="checkbox">
            </div>
            <div class="goods_info fl">
              <div class="img fl">
                <img src="${item.img}"
                  alt="">
              </div>
              <div class="title fl">
                ${item.title}
              </div>
              <div class='params fl'>
                <ul class='clearfix'>
                  ${parastr}
                </ul>
              </div>
            </div>
            <div class="goods_category fl">
              库存<span class='store-count'>${item.store}</span>件
            </div>
            <div class="unit_price fl">
              ￥${item.unit_price}
            </div>
            <div class="goods_counter fl">
              <div class="dec fl">-</div>
              <div class="count fl">
                <input type="text" value='${item.count}'>
              </div>
              <div class="inc fl">+</div>
            </div>
            <div class="subtotal fl">
            </div>
            <div class="delete fl">
              删除
            </div>
          </div>
          `;
        }).join(''));
      }else {
        $('#my-content-wrapper .cart_body').html(`
          <img id="empty" src="../static/images/shopCart/empty.jpg">
          <p class="gotobuy">
            <a href="./goodsList.html">立即选购</a>
          </p>
        `);
      }
    }
    //计算小计
    getSubtotal() {
      $('.cart-item').each((i, item) => {
        let unit_price = parseFloat($(item).find('.unit_price').text().trim().slice(1));
        let count = parseInt($(item).find('.goods_counter .count input').val().trim());
        $(item).find('.subtotal').text('￥' + (unit_price * count).toFixed(2));
      });
    }
    //将商品规格参数转化为对象
    transformParams(item) {
      let goods_params = [];
      item.find('.params li').each((i, ele) => {
        let key = $(ele).find('span.params-key').text().trim();
        let value = $(ele).find('span.params-value').text().trim();
        goods_params.push([key, value]);
      });
      return Object.fromEntries(goods_params);
    }
    //改变购物车商品数量，传入当前点击的cart-item
    putCartOptions(item) {
      let paramsObj = this.transformParams(item);
      let goodsid = item.attr('data-goodsid');
      for(let i=0; i<JSON.parse(localStorage.getItem(this.id)).length; i++) {
        if(goodsid === JSON.parse(localStorage.getItem(this.id))[i].goodsid && JSON.stringify(JSON.parse(localStorage.getItem(this.id))[i].params) === JSON.stringify(paramsObj)) {
          let number = parseInt(item.find('.goods_counter .count input').val().trim());
          let arr = JSON.parse(localStorage.getItem(this.id));
          arr[i].count = number;
          localStorage.setItem(this.id, JSON.stringify(arr));
        }
      }
    }
    //删除按钮购物车dom后，对应本地存储删除
    deleteLocalOne(goodsid, params) {
      let arr = JSON.parse(localStorage.getItem(this.id));
      let arr_new = arr.filter(item => {
        console.log(item.params, params);
        return item.goodsid !== goodsid || JSON.stringify(params) !== JSON.stringify(item.params);
      });
      localStorage.setItem(this.id, JSON.stringify(arr_new));
      location.reload();
    }

    //删除本地存储选中
    deletelocalSelect(idarr) {
      let arr = JSON.parse(localStorage.getItem(this.id));
      for(let i=0; i < idarr.length; i++) {
        for(let j=0; j < arr.length; j++) {
          if(idarr[i].goodsId === arr[j].goodsid && JSON.stringify(idarr[i].params) === JSON.stringify(arr[j].params)) {
            arr.splice(j, 1);
          }
        }
      }
      localStorage.setItem(this.id, JSON.stringify(arr));
      location.reload();
    }
    //清空购物车本地存储
    clearlocal() {
      localStorage.removeItem(this.id);
      location.reload();
    }
    //判断用户是否登录
    ifLogin() {
      if(!(this.token && this.id)) {
        new Toast({
          message: '用户未登陆或认证已过期，请您登录后再进行操作',
          color: '#E6A23C',
          callback() {
            location.href = './login.html';
          }
        });
      }
    }
  }
  new ShopCart();
});